package com.wyl.auth.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyl.auth.dto.SysRoleDto;
import com.wyl.auth.dto.SysRoleMenuDto;
import com.wyl.auth.entity.SysRole;
import com.wyl.auth.entity.SysRoleMenu;
import com.wyl.auth.entity.SysRolePermission;
import com.wyl.auth.entity.SysUserRole;
import com.wyl.auth.exception.BusinessException;
import com.wyl.auth.mapper.SysRoleMapper;
import com.wyl.auth.req.SysRoleReq;
import com.wyl.auth.service.SysRoleMenuService;
import com.wyl.auth.service.SysRolePermissionService;
import com.wyl.auth.service.SysRoleService;
import com.wyl.auth.service.SysUserRoleService;
import com.wyl.auth.util.BeanAwareUtil;
import com.wyl.auth.vo.SysRoleVo;
import com.wyl.common.CommonPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @Description 角色表
* @Author WuYiLong
* @Date 2025-04-03
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void save(SysRoleDto dto) {
        if(dto.getId() == null){
            SysRole sysRole = new SysRole();
            BeanAwareUtil.copyProperties(dto, sysRole);
            sysRole.setCreateTime(LocalDateTime.now());
            sysRole.setCreateUserId(StpUtil.getLoginIdAsLong());
            save(sysRole);
        }else{
            SysRole sysRole = getById(dto.getId());
            BeanAwareUtil.copyProperties(dto, sysRole);
            sysRole.setUpdateTime(LocalDateTime.now());
            sysRole.setUpdateUserId(StpUtil.getLoginIdAsLong());
            updateById(sysRole);
        }
    }

    @Override
    public CommonPage<SysRoleVo> page(SysRoleReq req) {
        Page<SysRole> page = new Page<>(req.getCurrentPage(), req.getPageSize());
        LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery(SysRole.class);
        wrapper.like(StrUtil.isNotBlank(req.getName()), SysRole::getName, req.getName());
        wrapper.eq(StrUtil.isNotBlank(req.getCode()), SysRole::getCode, req.getCode());
        Page<SysRole> sysRolePage = page(page, wrapper);
        List<SysRoleVo> sysRoleVos = sysRolePage.getRecords().stream().map(m -> {
            SysRoleVo sysRoleVo = new SysRoleVo();
            BeanAwareUtil.copyProperties(m, sysRoleVo);
            return sysRoleVo;
        }).collect(Collectors.toList());

        CommonPage<SysRoleVo> commonPage = new CommonPage<>();
        commonPage.setCurrentPage(req.getCurrentPage());
        commonPage.setPageSize(req.getPageSize());
        commonPage.setList(sysRoleVos);
        commonPage.setTotal((int)sysRolePage.getTotal());
        return commonPage;
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = Wrappers.lambdaQuery(SysUserRole.class);
        sysUserRoleLambdaQueryWrapper.in(SysUserRole::getRoleId, ids);
        long count = sysUserRoleService.count(sysUserRoleLambdaQueryWrapper);
        if(count > 0){
            throw new BusinessException("角色已挂用户，不可删除");
        }

        baseMapper.deleteBatchIds(ids);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignPermission(SysRoleMenuDto sysRoleMenuDto) {
        List<Long> menuIds = sysRoleMenuDto.getMenuIds();
        LambdaQueryWrapper<SysRoleMenu> sysRoleMenuLambdaQueryWrapper = Wrappers.lambdaQuery(SysRoleMenu.class);
        sysRoleMenuLambdaQueryWrapper.eq(SysRoleMenu::getRoleId, sysRoleMenuDto.getRoleId());
        sysRoleMenuService.remove(sysRoleMenuLambdaQueryWrapper);
        for (Long menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(sysRoleMenuDto.getRoleId());
            sysRoleMenuService.save(sysRoleMenu);
        }
        applicationContext.publishEvent(StpUtil.getLoginIdAsLong());
    }

    @Override
    public List<Long> listPermissionsByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = Wrappers.lambdaQuery(SysRoleMenu.class);
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> list = sysRoleMenuService.list(wrapper);
        List<Long> roleIds = list.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        return roleIds;
    }

    @Override
    public List<SysRoleVo> listRoles() {
        List<SysRole> list = list();
        List<SysRoleVo> sysRoleVos = list.stream().map(m -> {
            SysRoleVo sysRoleVo = new SysRoleVo();
            BeanAwareUtil.copyProperties(m, sysRoleVo);
            return sysRoleVo;
        }).collect(Collectors.toList());
        return sysRoleVos;
    }
}
